<?php
namespace pay;
use  think\Request;
use   think\Config;
date_default_timezone_set('PRC');
header("ontent-Type:text/html; charset=UTF-8");
class Yitianmao{

    private  $apiKey;
    private  $callback;
    private  $notify_url;
    public function __construct()
    {
            $class = strtolower("Yitianmao");

            $this->Config  = $Config = Config::get($class);
            $this->apiKey = $Config['apiKey'];

            $domain = Request::instance()->domain();
            //curl实例
            $this->http =new \http\Http();
        if(!empty($Config['callback_url'])){
            $this->callback = $Config['callback_url'];
        }else{
            $this->callback = $domain."/out/Notify/callbackurl";
        }
        if(!empty($Config['notify_url'])){
            $this->notify_url = $Config['notify_url'];
        }else{
            $this->notify_url =$domain."/out/Notify/handleyitian";
        }
    }

    //生成签名字符串
    private function Generationsign($sign){
        $Sign_last = substr(strtoupper(md5($sign)),0,16);
        return $Sign_last;
    }

    //获取处理的方法
    private function getGenerationAction($method){
            return $this->pay_action_url()[$method];
    }
    /**
     * @param $Context
     * @return mixed|string Content 处理
     */
    private function generationContext($Context){
        $Context1=base64_encode($Context);
        $Context1 = str_ireplace("+","-",$Context1);
        $Context1 = str_ireplace("/","_",$Context1);
        $Context1 = str_ireplace("=","",$Context1);
        return $Context1;
    }
    /**
     * @return string 网关支付
     */
    public function byPay($amount=1,$payNo,$pay_mode=""){
                $d_time = date("YmdHis");
                $configWay = $this->getGenerationAction(__FUNCTION__);
                $sysConfig = $this->sysConfigs();//获取系统处理

                $Generationsign = $configWay['Generationsign'];
                $tdata = ["trans_time"=>$d_time,
                    "app_id"=>$payNo,
                  //  "callback_url"=>urlencode($this->callback),
                    "notify_url"=>urlencode($this->notify_url),
                //   "amount"=>bcmul($amount,100),
                ];
                if(!empty($pay_mode)){
                    $tdata['pay_mode']  =$pay_mode;
                }
        $configWayBase=array_merge($configWay['Base'],$tdata);
        if(getOS()=="Linux"){
            error_log(json_encode($configWayBase,JSON_UNESCAPED_UNICODE).PHP_EOL,3,"/home/wwwlogs/ytm_parmas_base.log");
        }

        $data['context'] =  $this->generationContext(http_build_query($configWayBase));//base64之后
        $data['signature'] = $this->delwithSign($Generationsign,$configWayBase);
        $sys = array_merge($sysConfig,$data);

         $sysResult  =$this->http->post($configWay["url"],$sys);
        if(getOS()=="Linux"){
            error_log(json_encode($sys).PHP_EOL,3,"/home/wwwlogs/ytm_parmas.log");
        }
       $sysResult = mb_convert_encoding($sysResult, "UTF-8","GBK");
        $sysResult = json_decode($sysResult,true);
        if(getOS()=="Linux"){
            error_log(json_encode($sysResult).PHP_EOL,3,"/home/wwwlogs/ytm.log");
        }
        if(isset($sysResult['errorcode'])&&$sysResult['errorcode']=="0000"){
           $result =   base64_decode($this->UnPackUrlBase64($sysResult['context']));
            parse_str($result,$result);
            $result['pay_url'] = base64_decode($this->UnPackUrlBase64($result['pay_url']));

           return $result['pay_url'];
        }
        return $sysResult;

    }
    public function Notify($content){
                //加密的字符串

        $tdata = ["msg"=>"异常","status"=>0,"data"=>[]];
        parse_str($content,$result);
        $result = base64_decode($this->UnPackUrlBase64($result['context']));
        parse_str($result,$result);
        //异步流处理

        $strSign=$result["signature"]; //秘钥
        $NotifySignModel  = new \app\admin\model\UsersRecharge();
        $res = $NotifySignModel->where("thirdparty_payno",$result['trans_id'])->find();
        if($res['status']==2){
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已失效"]);
        }
        if($res['status']==1){
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已充值成功"]);
        }
        $resultBa['trans_id'] =$result['trans_id'];
        $resultBa['result'] =$result['result'];
        $resultBa['amount'] =$result['amount'];
        $NotifySign = ["trans_id","result","amount"];
       $sign= $this->delwithSign($NotifySign,$resultBa);

       if($strSign==$sign){

          return  ["data"=>$result,"status"=>1,"msg"=>"验证成功"];
       }

        return $tdata;

    }

    //处理恶心的加密
    private function delwithSign($Generationsign,$configWayBase){
            $signString = [];
         array_filter($configWayBase,function($val,$key)use($Generationsign,&$signString){
                                if(in_array($key,$Generationsign)){
                                    $signString[] = "{".$val."}";
                                }
         },ARRAY_FILTER_USE_BOTH);

         if(!empty($signString)){
                array_push($signString,"{".$this->apiKey."}");
         }
        $swith = implode("|",$signString);

        if(getOS()=="Linux"){
            error_log(json_encode($swith,JSON_UNESCAPED_UNICODE).PHP_EOL,3,"/home/wwwlogs/Sign.log");
        }

        $Sign = substr(strtoupper(md5($swith)),0,16);

        return $Sign;

    }

    //配置基础系统传参
    private function sysConfigs(){
        $data=array(
            "syscode"=>$this->Config['syscode'],
            "version"=>$this->Config['version'],
            "context" => "",
            "signature"=> "",
        );
        return $data;
    }

    private function pay_action_url(){
        $pay_action_url=[
            "byPay"=>[//支付网关配置
               //"url"=>"http://www.yitianmao.com/cgi-bin/gateway_pay.cgi",
                "url"=>"http://www.yitianmao.com/cgi-bin/qpay_cu_contract.cgi",
                "Generationsign"=>["server_no","trans_time","account","pay_mode","aging","card_no","card_type","id_type","id_no","mobile"],
                "Base"=>[
                    "server_no"=>200001,
                    "trans_time"=>"",
                    "account"=>$this->Config['account'],
                    "account_sign"=>$this->Config['account'],
                    "pay_mode"=>"API_CUQPAY",
                    "aging"=>$this->Config['aging'],
                    "app_id"=>"",
                    "card_name"=>"胡顺适",
                    "card_no"=>"6222023202040484742",
                    "card_type"=>"01",
                    "id_type"=>"01",
                    "notify_url"=>$this->notify_url,
                   " id_no"=>"6222023202040484742",
                    "mobile"=>"13554094775",

                   // "callback_url"=>$this->callback,
                    ]
            ],

        ];
      /*  {server_no}|
        {trans_time}|
        {account}|
        {pay_mode}|
        {aging}|
        {card_no}|
        {card_type}|
        {id_type}|
        {id_no}|
        {mobile}|*/

        /*
                交易代码	server_no	6	Y	交易代码   200001
        交易时间	trans_time	14	Y	交易时间 YYYYMMDDHHMMSS
        商户号	account	10	Y	商户号，系统对接提供。
        注册商户号	account_sign	10	Y	长度10位以下的数字
        同一个注册商户号，可以签多张卡
        支付方式	pay_mode	30	Y	API_CUQPAY
        支付时效	aging	3	Y	支付时效1：D0 2：T1
        商户流水号	app_id	30	C	商户的流水号，商户须保证唯一
        通知URL	notify_url	128	Y	商户实现的接收异步通知的url地址
        持卡人姓名	card_name	32	Y	持卡人姓名
        持卡卡号	card_no	4	Y	持卡卡号
        卡类型	card_type	2	Y	00   贷记卡
        01   借记卡
        02   准贷记卡
        有效期 	card_expdate	4	C	信用卡有效期cardType为00 时必填
        格式：年月 如：2008 对应2020年08月
        安全码	card_cvv	3	C	Cvv2信用卡有效期cardType为00 时必填
        银行编码	bank_code	8	N	银行编码
        开户银行	bank_name	32	N	开户银行
        证件类型	id_type	2	Y	证件类型 01身份证
        证件号码	id_no	18	Y	证件号码
        手机号	mobile	11	Y      	手机号
        交易签名	signature	16	Y	{参数}代表参数的具体值*/



       /* {server_no}|
        {trans_time}|
        {account}|
        {pay_mode}|
        {aging}|
        {card_no}|
        {card_type}|
        {id_type}|
        {id_no}|
        {mobile}|*/

        return $pay_action_url;
    }

    private  function UnPackUrlBase64($strdata) {
        $strdata = str_ireplace("-","+",$strdata);
        $strdata = str_ireplace("_","/",$strdata);
        while (strlen($strdata) % 4 != 0)
        {
            $strdata .= "=";
        }

        return $strdata;
    }





}
?>
